﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;
using System.IO;
using Baidu.Aip.Face;
using Newtonsoft.Json.Linq;

namespace Common
{
  public class BaiduFaceSetting
  {
    [JsonIgnore]
    public string AppID { get; set; }

    [JsonIgnore]
    public string APIKey { get; set; }

    [JsonIgnore]
    public string SecretKey { get; set; }


    [JsonIgnore]
    public string GroupId { get; set; }

    [JsonIgnore]
    public string GroupIdList { get; set; }

  }

  public class BaiduFaceConfig
  {

    private static BaiduFaceSetting _config = null;
    public static BaiduFaceSetting Current
    {
      get
      {
        if (_config == null)
        {
          _config = ConfigurationManager.GetSection<BaiduFaceSetting>("BaiduFaceSetting");
        }
        return _config;
      }
    }
  }

  public class FaceCheckHelper
  {   
    /// <summary>
    /// 从平台获取人员图片
    /// </summary>
    /// <param name="uid"></param>
    /// <param name="testUnit"></param>
    /// <returns></returns>
    public static string GetReferenceImg(string uid,string testUnit)
    {

      return "";
    }

    /// <summary>
    /// 保存检测人员平台照片
    /// </summary>
    /// <param name="uid"></param>
    /// <param name="imgBase64Str"></param>
    /// <returns></returns>
    public static bool SaveReferenceImg(string uid, string imgBase64Str)
    {
      return true;
    }

    public static bool check(string img, string uid)
    {
      var API_KEY = BaiduFaceConfig.Current.APIKey;
      var SECRET_KEY = BaiduFaceConfig.Current.SecretKey;
      var client = new Face(API_KEY, SECRET_KEY);
      string referenceImg = PublicTool.GetReferenceImg(uid);
      
      referenceImg = referenceImg[(referenceImg.IndexOf(",") + 1)..];
      string submitImg = img[(img.IndexOf(",") + 1)..];

      var faces = new JArray{
        new JObject{
          {"image",submitImg },
          {"image_type", "BASE64"},
          {"face_type", "LIVE"},
          {"quality_control", "HIGH"},
          {"liveness_control", "HIGH"},
        },
        new JObject{
          {"image", referenceImg},
          {"image_type", "BASE64"},
          {"face_type", "LIVE"},
          {"quality_control", "HIGH"},
          {"liveness_control", "HIGH"},
        }
      };

      var result = client.Match(faces);
      //var apicode = ""; var msg = "";
      //if (result["error_code"].ToString() != "0")
      //{
      //  Log.Error("{0}人脸比对返回数据:{1}", UserKey, JsonConvert.SerializeObject(result));
      //  apicode = result["error_code"].ToString();
      //  msg = result["error_msg"].ToString();
      //}
      //else
      //{
      //  Log.Information("{0}人脸比对返回数据:{1}", UserKey, JsonConvert.SerializeObject(result));
      //  apicode = result["error_code"].ToString();
      //  msg = result["result"]["score"].ToString();
      //}

      return true;

    }
  }
}
